package life.sweet.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import life.sweet.community.dto.AccessTokenDTO;
import life.sweet.community.dto.MayunUser;
import okhttp3.*;
import org.springframework.stereotype.Component;


import java.io.IOException;

@Component
public class MayunProvider {
    public String getAccessToken(AccessTokenDTO dto) {
        MediaType mt = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mt, JSONObject.toJSONString(dto));
        Request request = new Request.Builder()
                .addHeader("Accept","application/json").addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
                .url("https://gitee.com/oauth/token?code=" + dto.getCode()+ "&client_id=" + dto.getClient_id()
                        + "&" + "redirect_uri="+ dto.getRedirect_uri()+"&client_secret="
                        + dto.getClient_secret() + "&grant_type=authorization_code")
                .post(body)
                .build();
        AccessTokenDTO acDto = new AccessTokenDTO();
        try (Response response = client.newCall(request).execute()) {
            try {
                String st = response.body().string();
                acDto = JSON.parseObject(st,AccessTokenDTO.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return acDto.getAccess_token();
    }

    public MayunUser getUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try {
            Response resp = client.newCall(request).execute();
            String respStr = resp.body().string();
            MayunUser user = JSON.parseObject(respStr, MayunUser.class);
            return user;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
